import express from 'express';
import db from './../lib/DbHelper';
import fs from 'fs';
//import async1 from 'async';
let router = express.Router();


//登录接口
router.post("/login", (req, res, next) => {
    let sql = "SELECT `uid`,`uname`,`uemail`FROM `cs1903h5-1`"
    sql += " WHERE uname=? AND upwd=?";
    let params = [req.body.uname, req.body.upwd]

    var resultObj = {
        "msg": "登录失败咯",
        status: -1
    }

    db.query(sql, params).then((result) => {
        if (result.length > 0) {
            resultObj.data = result[0];
            resultObj.msg = "登录成功哟哟哟";
            resultObj.status = 1;
        }
        res.json(resultObj);
    }).catch((err) => {
        resultObj.err = err;
        res.json(resultObj);
    });

})


//注册接口
router.post("/reg", (req, res, next) => {
    let sql = "INSERT INTO `cs1903h5-1`(`uname`,`upwd`,`uemail`)VALUES(?,?,?)";
    let params = [
        req.body.uname,
        req.body.upwd,
        req.body.uemail
    ]
    db.queryAsync(sql, params).then((data) => {
        if (data.affectedRows == 1) {
            res.json({
                "msg": "注册成功哟",
                status: 1
            })
        } else {
            res.json({
                "msg": "注册失败哟",
                status: -1
            })
        }
    }, (err) => {
        res.json({
            "msg": "注册失败哟",
            status: -2,
            err
        })
    })
})

//检查用户名是否存在
router.post("/checkname", (req, res, next) => {
    var userObj = req.body.uname;
    let sql = "SELECT COUNT(*) AS COUNT FROM `cs1903h5-1` WHERE `uname`=? ";
    // let params=[userObj];
    db.query(sql, userObj).then((data) => {
        if (data[0].COUNT >= 1) {
            res.json({
                "msg": "用户已注册",
                "status": -1
            })
        } else {
            res.json({
                "msg": "用户可以注册",
                "status": 1
            })
        }
    })
})

//产品列表
router.get("/goods", (req, res, next) => {


    var tmpPid = req.query.pid == undefined ? 0 : req.query.pid; //接收前端发过来的url带有得到他的参数


    var goodsStr = fs.readFileSync("./data/goodsList.json", {
        encoding: "utf-8",
        flag: "r"
    });
    const goodsList = JSON.parse(goodsStr);
    var queryList = goodsList.filter((el) => {
        return el.pid == tmpPid;
    })
    if (req.query.pid == undefined) {
        res.json(goodsList);
    } else {
        res.json(queryList)
    }



    res.json(queryList);


    // console.log(JSON.parse(goodsStr));
    // res.end();
})



//加入购物车
router.post("/addCart", async (req, res, next) => {
    //sql语句 查询
    const searchsql = "SELECT * FROM`carts`WHERE pId=?AND uid=?";
    var searchParams = [req.body.pId, req.body.uId]
    //params
    let queryData =await db.queryAsync(searchsql, searchParams);

    if(queryData.length>=1){
        //3修改
        var updateSQL = "UPDATE `carts` SET pNum=pNum+?,pTotal=pNum*pPrice WHERE uid=? AND pid=?"
        var updateParams = [
            req.body.pNum,
            req.body.uId,
            req.body.pId,
        ]
        let updateData = await db.queryAsync(updateSQL, updateParams);
        console.log(updateData)
        if(updateData.affectedRows>=1){
                res.json({
                    msg:"加入成功",
                    status:1 
                })
            }else{
                res.json({
                    msg:"加入失败",
                    status:-1
                })
            }
        
    }else{
         //2 插入
         var insertSQL = "INSERT	INTO `carts`(`uid`,`pid`,`pName`,`pPrice`,`pNum`,`pTotal`,`pImg`)VALUES(?,?,?,?,?,?,?)"
         var insertParams = [
             req.body.uId,
             req.body.pId,
             req.body.pName,
             req.body.pPrice,
             req.body.pNum,
             req.body.pTotal,
             req.body.pImg
         ]
         let insertData = await db.queryAsync(insertSQL, insertParams);
          if(insertData.affectedRows>=1){
                res.json({
                    msg:"加入成功哦",
                    status:2
                })
            }else{
                res.json({
                    msg:"加入失败哦",
                    status:-2
                })
            }
    }

})

//放进购物车页面


router.get("/getCarts",async (req,res,next)=>{
    let uid=req.query.uId;
    let sql="SELECT * FROM `carts` WHERE uid=?";
    let params=[uid];
    const result =await db.query(sql,params);
   
    res.json(result);

})


//修改购物车
router.post("/modify",async (req,res,next)=>{
    var params=[req.body.pNum,req.body.uId,req.body.pId];
    var sql="UPDATE `carts` SET pNum=?,pTotal=pNum*pPrice WHERE uid=? AND pid=?";
    var result= await db.query(sql,params);
    res.json(result);

})


//删除购物车
router.post("/delete",async (req,res,next)=>{
    var params=[req.body.uId,req.body.pId];
    var sql="DELETE FROM `carts` WHERE uid=?AND pid=?";
    var result= await db.query(sql,params);
    res.json(result);

})










module.exports = {
    router
}